package surfing.chatting.ui.panel;

import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;

import javax.swing.BoxLayout;
import javax.swing.JPanel;

import surfing.chatting.client.Client;
import surfing.chatting.client.User;

public class PanelList extends JPanel {
	private static final long serialVersionUID = 7487708333367358427L;
	private int atLabel = 1;
	LinkedList<User> onlineList = new LinkedList<User>();
	LinkedList<User> offlineList = new LinkedList<User>();

	public PanelList() {
		super();
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		// addLabel(Client.me.group);
		// addLabel(Client.me.robot);
	}

	public int getAtLabel() {
		return atLabel;
	}

	public void setAtLabel(int atLabel) {
		this.atLabel = atLabel;
	}

	public void movScrollbar(User user) {
		int value = (this.getComponentZOrder(user.getLabel()) - 6) * 80;
		PanelChatMidle.getScrollpane().getVerticalScrollBar().setValue(value);
	}

	public void addLabel(Map<String, User> map) {
		User user;
		for (String id : map.keySet()) {
			user = Client.myList.getUserMap().get(id);
			user.getLabel().setPanel(this);
			if (user.isOnline()) {
				onlineList.add(user);
			} else {
				offlineList.add(user);
			}
		}
		Collections.sort(onlineList);
		Collections.sort(offlineList);

		for (User user1 : onlineList) {
			this.add(user1.getLabel());
		}
		for (User user1 : offlineList) {
			this.add(user1.getLabel());
		}
	}

	public void addLabel(User user) {
		user.getLabel().setPanel(this);
		if (user.isOnline()) {
			onlineList.add(user);
			Collections.sort(onlineList);
			if (offlineList.contains(user)) {
				offlineList.remove(user);
				this.remove(user.getLabel());
			}
			this.add(user.getLabel(), onlineList.indexOf(user));
		} else {
			offlineList.add(user);
			Collections.sort(offlineList);
			if (onlineList.contains(user)) {
				onlineList.remove(user);
				this.remove(user.getLabel());
			}
			this.add(user.getLabel(), onlineList.size() + offlineList.indexOf(user));
		}
		this.updateUI();
	}

	public void setSelectedLabel(User user) {
		user.getLabel().setSelected(this);
		movScrollbar(user);
	}
}
